package com.ccp.dev.system.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.system.dao.RoleResourcesDao;
import com.ccp.dev.system.model.RoleResources;
import com.ccp.dev.system.model.SysRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

;

/**
 * 角色资源映射 Service类
 * @author y
 */
@Service
public class RoleResourcesService extends BaseService<RoleResources> {
	@Resource
	private RoleResourcesDao roleResourcesDao;
	@Resource
	private SysRoleService sysRoleService;

	/**
	 * 更新角色资源
	 * @param roleId	角色id
	 * @param resId		资源id数组
	 */
	@Transactional(rollbackFor = Exception.class)
	public void roleAddRes(String roleId , String[] resId) throws Exception{
		SysRole sysRole = sysRoleService.get(roleId);
		if(SysRole.DEFAULT_THREEROLE.equals(sysRole.getIsPublic())){
			throw new Exception("sysUser.editUser.threeUserWarning");
		}
		sysRoleService.publicRoleWarning(roleId);
		//删除
		Map<String,Object> map = new HashMap<>();
		map.put("systemId", sysRole.getSystemId());
		map.put("roleId", roleId);
		this.roleResourcesDao.delByRoleAndSys(map);
		//添加角色和资源的映射。
		if(resId != null){
			Set<String> set = new HashSet<>(Arrays.asList(resId));
			RoleResources roles=new RoleResources();
			for(String id : set){
				roles.setRoleResId(UUIDUtils.getUUIDFor32());
				roles.setResId(id);
				roles.setSystemId(sysRole.getSystemId());
				roles.setRoleId(roleId);
				roleResourcesDao.add(roles);
			}
		}
	}
}
